#!/bin/bash

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/../common.sh"

function install_development() {
  sudo yum install -y wget tar environment-modules
  source /etc/profile
}

function download_gsl() {
  echo "# GSL-2.5 正在下载"
  wget -t 10 -T 20 -c -P "$1" http://mirrors.ustc.edu.cn/gnu/gsl/gsl-2.5.tar.gz
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# GSL-2.5 已经下载成功\033[0m"
  else
    echo -e "\033[31m# GSL-2.5 下载失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function install_gsl() {
  echo "# GSL-2.5 正在安装"
  tar -xzf "$1"/gsl-2.5.tar.gz -C "$1" && rm -rf "$1"/gsl-2.5.tar.gz
  cd "$1"/gsl-2.5
  ./configure CC=clang --prefix="$2"/gsl-2.5
  make -j"$(nproc)" && make install
  echo -e "\033[1;32;1m# GSL-2.5 已经安装完毕\033[0m"
}

function write_gsl-2.5_module() {
  cat >"$1/gsl-2.5/gsl_modulefiles" <<EOF
#%Module1.0
conflict gsl
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
  variable modfile
  set modfile_path [file dirname \$modfile]
  return \$modfile_path
}
set pwd [getModulefileDir]
set GSL \$pwd
setenv GSL \$GSL
prepend-path PATH \$GSL/bin
prepend-path LIBRARY_PATH \$GSL/lib
prepend-path LD_LIBRARY_PATH \$GSL/lib
prepend-path CPLUS_INCLUDE_PATH \$GSL/include
prepend-path C_INCLUDE_PATH \$GSL/include
EOF
}

function main() {
  set -e
  is_check_build_install_directory "$1" "$2" "gsl-2.5.sh"
  is_check_build_equal "$1" "$2"
  install_development
  download_gsl "$1"
  install_gsl "$1" "$2"
  write_gsl-2.5_module "$2"
  rm -rf "$1"/gsl-2.5
}

main "$@"
